package com.lxk.concurrency.example.aqs;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Semapphore：对并发访问的控制，限制并发量
 * @author leong
 *
 */
public class SemapphoreExample3 {

	private final static int threadCount = 20;

	public static void main(String[] args) throws Exception {

		ExecutorService exec = Executors.newCachedThreadPool();

		final Semaphore semaphore = new Semaphore(3);

		for (int i = 0; i < threadCount; i++) {
			final int threadNum = i;

			exec.execute(() -> {
				try {

					// 获取一个许可，获取到就执行
					if (semaphore.tryAcquire()) {
						test(threadNum);
						semaphore.release(); // 释放一个许可
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			});
		}

		// 关闭线程池
		exec.shutdown();
	}

	private static void test(int threadNum) throws Exception {
		System.out.println(threadNum);
		Thread.sleep(1000);
	}
}
